﻿using CoreShop.Model;
using CoreShop.Services;
using FastMember;
using SqlSugar.Extensions;
using Sunny.UI;
using Newtonsoft.Json;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using CoreShop.Library;
using static System.Windows.Forms.VisualStyles.VisualStyleElement;
using System.ComponentModel;

namespace CoreShop.PrintService
{
    public class PrinterManager
    {
        public static JsPrinter jsPrinter = null;//通用打印机,corecmsprintscheme.brandId = 0
        public static XyPrinter xyPrinter = null;//芯烨打印机,corecmsprintscheme.brandId = 2
        public static JbPrinter jbPrinter = null;//佳博打印机,corecmsprintscheme.brandId = 1

        public static List<PrintServices> PrinterList = new List<PrintServices>();

        /// <summary>
        /// 初始化打印机并添加到列表
        /// </summary>
        public static void InitPrinterAll()
        {
            PrinterList.Clear();
            //var list = new corecmsprintschemeServices().QueryAsync((int)GlobalEnumVars.SendPrintWay.Command);
            var list = new corecmsprintschemeServices().GetKitchenPrinter();
            var printschemeIds = list.Select(p=>p.id).ToList();

            var listDetails = new corecmsprintschemedetailServices().AsQueryable()
                .Where(p=> printschemeIds.Contains(p.printSchemeId) && p.selectedFlag == true).ToList();

            var templateIds = listDetails.Select(p=>p.templateId).ToList();
            var billtemplateList = new corecmsprintbilltemplateServices().AsQueryable().Where(p => templateIds.Contains(p.id)).ToList();

            foreach (var printscheme in list)
            {
                var schemedetails = listDetails.Where(p=>p.printSchemeId == printscheme.id).ToList();
                if (schemedetails == null) continue;
                foreach (var schemedetail in schemedetails)
                {
                    var billtemplate = billtemplateList.Find(p => p.id == schemedetail.templateId);
                    if (billtemplate != null) schemedetail.billtemplate = billtemplate;
                }
                printscheme.printschemedetails = schemedetails;
                InitPrinter(printscheme);
            }
        }

        /// <summary>
        /// 初始化打印机并添加到列表
        /// </summary>
        public static void InitPrinter(corecmsprintscheme printscheme)
        {
            bool isInit = false;
            foreach (PrintServices printer in PrinterList)
            {
                if (printer.IPAddress == printscheme.printerIP) isInit = true;
            }

            if (isInit) return;

            PrintServices printServices = new PrintServices();
            printServices.IPAddress = printscheme.printerIP;
            printServices.PrintSchemeInfo = printscheme;
            //printscheme.Linked = printServices.OpenPrinter();            
            PrinterList.Add(printServices);
        }
               
    }
}